#include "mystdio.h"
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
myFILE* setFILE(int _fg, int _fd)
{
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(fp == NULL) return NULL;
    fp->fd = _fd;
    fp->flag = _fg;
    fp->buffSize=0;
    memset(fp->buffers, 0, N);
    return fp;
}
myFILE* myfopen(char* str,char* way)
{
    int fd = -1,flag = 0;
    if(strcmp(way,"w")==0)
    {

        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(str, flag, 0664);
    }
    else if(strcmp(way,"r")==0)
    {
        flag = O_RDWR;
        fd = open(str, flag, 0664);
    }
    else if(strcmp(way,"a")==0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND; 
        fd = open(str, flag, 0664);
    }
    else 
    {
        //more
    }
    if(fd < 0)
    {
        printf("myfopen error\n");
        return NULL;
    }
    return setFILE(flag, fd);
}
void myfwrite(char* str,size_t sz,myFILE* fp)
{
    memcpy(fp->buffers+fp->buffSize,str,sz);
    fp->buffSize += sz;
    if(str[sz-1]=='\n')
        myfflush(fp);
}
void myfclose(myFILE* fp)
{
    myfflush(fp);
    close(fp->fd);
    free(fp);
    fp = NULL;
}
void myfflush(myFILE* fp)
{
    write(fp->fd,fp->buffers,fp->buffSize);
    fp->buffSize = 0;
}

